<?php

namespace app\award;

use app\models\NewLevel;
use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\OrderActive;
use app\models\product\Product;
use app\models\product\ProductArea;
use app\models\Queue;
use app\models\SetProductCommission;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\services\Chain;
use app\util\Util;

class Award
{
    protected $order;
    protected $user;

    protected $set;

    protected $total_pay;

    public function __construct(Order $order)
    {
        $this->order = $order;
        $this->user = User::findOne(['id' => $this->order->user_id]);

        $this->total_pay = $this->order->total_pay - $this->order->total_freight;

        $first_order_item = OrderItem::find()
            ->where(['order_id' => $order->id])
            ->orderBy(['id' => SORT_ASC])
            ->limit(1)
            ->one();
        $product_id = $first_order_item->product_id;

        $this->set = SetUserUp::getLastOne();

        $is_bao = ProductArea::checkBao($product_id);
        $is_repeat = ProductArea::checkRepeat($product_id);
        $is_general = ProductArea::checkGeneral($product_id);
        $is_presale = ProductArea::checkPresale($product_id);

        if ($is_bao || $is_repeat) {

            // 记录区, 分红时好计算
            $this->order->area = 1;
            $this->order->save();
        }

        // 新报单
        if ($is_bao) {
            $this->bao(true);
            $this->jd();

            // 两个分红
            $this->other();
        }

        // 普通商品区
        if ($is_general) {
            $this->general();
        }

        // 复购区
        if ($is_repeat) {
            $this->diff();

            // 两个分红
            $this->other();
        }

        // 预售商品
        if ($is_presale) {

            // 改状态
            $this->order->status = Order::$statusMapping['FINISH'];
            $this->order->save();

            // 新的, 生成激活码
            $items = OrderItem::find()
                ->where(['order_id' => $this->order->id])
                ->all();

            foreach ($items as $item) {
                for ($i = 0; $i < $item['quantity']; $i++) {
                    $active_code = Util::generateNonceString(8);
                    $active = new OrderActive();
                    $active->active_code = $active_code;
                    $active->active_status = 0;
                    $active->order_id = $this->order->id;
                    $active->order_item_id = $item['id'];
                    $active->save();
                }
            }

            if ($this->order->active_ok == 0) {
                // 生成激活码
                $this->order->active = Util::generateNonceString(8);
                $this->order->save();

            } else {
                // 取消了激活操作, 直接用激活码支付了
                // $this->bao(true);
                // $this->equal();
            }


        }
    }

    // 另两个身份分红
    public function other()
    {
        $total_amount = $this->order->total_pay - $this->order->total_freight;

        $svip1 = User::find()
            ->where(['level' => UserLevel::$keys['svip1']])
            ->all();
        // var_dump($this->set->svip1 / 100 * $total_amount);exit;
        if ($svip1) {
            $commission = $this->set->svip1 / 100 * $total_amount / count($svip1);
            foreach ($svip1 as $user) {
                $this->saveCommission2($user->id, $commission, 199, '分红');
            }
        }

        $svip2 = User::find()
            ->where(['level' => UserLevel::$keys['svip2']])
            ->all();
        if ($svip2) {
            $commission = $this->set->svip2 / 100 * $total_amount / count($svip2);
            foreach ($svip2 as $user) {
                $this->saveCommission2($user->id, $commission, 198, '分红');
            }
        }
    }

    // 分红月奖
    // public function profit()
    // {
    //     $queue = new Queue();
    //     $queue->order_id = $this->order->id;
    //     $queue->status = 0;
    //     $queue->save();
    // }

    // 处理分红
    // public function exeProfit()
    // {
    //     set_time_limit(60 * 60 * 24);
    //
    //     // 由于队列可能中断,
    //     // 如果这笔订单已经返了, 就不操作了
    //     $is = UserCommission::find()
    //         ->where(['order_id' => $this->order->id])
    //         ->andWhere(['award_type' => 30])
    //         ->one();
    //     if ($is) {
    //         return;
    //     }
    //
    //     $list = Profit::getList($this->order->user_id);
    //
    //     var_dump($list);exit;
    //
    //     $type = 30;
    //     $name = '分红';
    //
    //     foreach ($list as $item) {
    //         $this->saveCommission($item['id'], $item['amount'], $type, $name);
    //         echo '佣金: ', $item['id'], ' , 金额: ', $item['amount'], "\n";
    //     }
    // }

    // 复购差价奖
    public function diff()
    {
        $award_name = '差价';
        $award_type = 55;

        $has_vip1 = false;
        $has_vip2 = false;
        $has_vip3 = false;
        $has_vip4 = false;

        $diff_vip1 = 0;
        $diff_vip2 = 0;
        $diff_vip3 = 0;
        $diff_vip4 = 0;

        $chain = Chain::getReferrerChain($this->order->user_id, [
            UserLevel::$keys['vip1'],
            UserLevel::$keys['vip2'],
            UserLevel::$keys['vip3'],
            UserLevel::$keys['vip4']
        ], true);

        foreach ($chain as $user) {
            if ($user->level <= $this->user->level) {
                continue;
            }

            if ((!$has_vip1 && !$has_vip2 && !$has_vip3 && !$has_vip4) && $user->level == UserLevel::$keys['vip1']) {
                $diff_vip1 = $this->_diff('vip1');
                $this->saveCommission($user->id, $diff_vip1, $award_type, $award_name);
                $has_vip1 = true;
            }
            if ((!$has_vip2 && !$has_vip3 && !$has_vip4) && $user->level == UserLevel::$keys['vip2']) {
                $diff_vip2 = $this->_diff('vip2');
                $diff_vip2 -= $diff_vip1;
                $this->saveCommission($user->id, $diff_vip2, $award_type, $award_name);
                $has_vip2 = true;
            }
            if ((!$has_vip3 && !$has_vip4) && $user->level == UserLevel::$keys['vip3']) {
                $diff_vip3 = $this->_diff('vip3');
                $diff_vip3 -= $diff_vip2 + $diff_vip1;
                $this->saveCommission($user->id, $diff_vip3, $award_type, $award_name);
                $has_vip3 = true;
            }
            if ((!$has_vip4) && $user->level == UserLevel::$keys['vip4']) {
                $diff_vip4 = $this->_diff('vip4');
                $diff_vip4 -= $diff_vip2 + $diff_vip3 + $diff_vip1;
                $this->saveCommission($user->id, $diff_vip4, $award_type, $award_name);
                $has_vip4 = true;
                break;
            }
        }
    }

    private function _diff($diff_key)
    {
        $order_items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $sum = 0;

        foreach ($order_items as $item) {
            $product = SetProductCommission::findOne(['product_id' => $item->product_id])->toArray();
            $sum += ($item['price'] - $product[$diff_key]) * $item['quantity'];
        }

        return $sum;
    }

    // 普通商品区
    // 返2层, 20%
    public function general()
    {
        $amount = $this->total_pay * $this->set->general / 100;

        $r1 = Chain::getReferrer($this->user->id, true);
        if ($r1) {
            if ($r1->level >= UserLevel::$keys['vip1']) {
                $commission = $amount;
                $this->saveCommission($r1->id, $commission, 101, '商品区直推');

                $r2 = Chain::getReferrer($r1->id, true);
                if ($r2 && $r2->level >= UserLevel::$keys['vip1']) {
                    $commission = $amount * $this->set->general / 100;
                    $this->saveCommission($r2->id, $commission, 102, '商品区间推');
                }
            }
        }
    }

    // 报单区
    public function bao($active = false)
    {
        // 购买送积分
        // $this->saveScore($this->user->id, $this->total_pay);

        $items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->asArray()
            ->all();

        foreach ($items as $item) {
            if ($active || $item['price'] >= $this->set->vip1) {
                // 购买车已经被限制了, 所以这里数量为1
                $this->_bao($item['quantity']);
            }
        }
    }

    public function _bao($quantity = 1)
    {
        $award_name1 = '直推奖';
        $award_type1 = 201;

        $award_name2 = '管理奖';
        $award_type2 = 202;

        $r1 = Chain::getReferrer($this->user->id, true);
        if ($r1) {
            if ($r1->level >= UserLevel::$keys['vip2']) {
                $this->saveCommission($r1->id, $this->set->r1, $award_type1, $award_name1);
                $this->saveCommission($r1->id, $this->set->r2, $award_type2, $award_name2);
                // 平级
                $this->equal($r1->id, $this->set->r1);
                $this->equal($r1->id, $this->set->r2);
            } else if ($r1->level == UserLevel::$keys['vip1']) {
                $this->saveCommission($r1->id, $this->set->r1, $award_type1, $award_name1);
                // 平级
                $this->equal($r1->id, $this->set->r1);
                // 间推
                $r2 = $this->getIndirect($r1->id);
                if ($r2) {
                    $this->saveCommission($r2->id, $this->set->r2, $award_type2, $award_name2);
                    // 平级
                    $this->equal($r2->id, $this->set->r2);
                }
            }

            //
            // if ($r1->level == UserLevel::$keys['vip1']) {
            //     // 会员直推留下20%, 升级再返
            //     $this->saveCommission($r1->id, $this->set->r1 * $quantity * 0.8, $award_type1, $award_name1);
            //     $this->saveCommission($r1->id, $this->set->r1 * $quantity * 0.2, $award_type1, $award_name1, 0);
            //
            //     // $this->_second($r1, $quantity);
            //     $this->_second($this->user, $quantity);
            //
            // } else if ($r1->level > UserLevel::$keys['vip1']){
            //     $this->saveCommission($r1->id, $this->set->r1 * $quantity, $award_type1, $award_name1);
            //
            //     // $this->_second($r1, $quantity);
            //     $this->_second($this->user, $quantity);
            // }
        }
    }

    // 最终的平级奖
    public function equal($user_id, $amount)
    {
        $award_name = '平级奖';
        $award_type = 203;

        $r1 = Chain::getReferrer($user_id,true);
        if ($r1 && $r1->level >= UserLevel::$keys['vip2']) {
            $commission = $this->set->equal / 100 * $amount;
            $this->saveCommission($r1->id, $commission, $award_type, $award_name);

            $r2 = Chain::getReferrer($r1->id,true);
            if ($r2 && $r2->level >= UserLevel::$keys['vip2']) {
                $commission = $this->set->equal / 100 * $commission;
                $this->saveCommission($r2->id, $commission, $award_type, $award_name);
            }
        }
    }

    // 见单 差价
    public function jd()
    {
        $award_name3 = '见单奖1';
        $award_type3 = 203;
        $award_name4 = '见单奖2';
        $award_type4 = 204;

        $chain = Chain::getReferrerChain($this->user->id, [
            UserLevel::$keys['vip3'],
            UserLevel::$keys['vip4']
        ], true);

        $vip3 = 0;
        $vip4 = 0;

        $has_vip3 = false;
        $has_vip4 = false;

        foreach ($chain as $u) {
            if ((!$has_vip3 && !$has_vip4) && $u->level == UserLevel::$keys['vip3']) {
                $vip3 = $this->set->r3;
                $this->saveCommission($u->id, $vip3, $award_type3, $award_name3);
                $this->equal($u->id, $vip3);
                $has_vip3 = true;
            }
            if ((!$has_vip4) && $u->level == UserLevel::$keys['vip4']) {
                if (!$has_vip3) {
                    $vip3 = $this->set->r3;
                    $this->saveCommission($u->id, $vip3, $award_type3, $award_name3);
                    $this->equal($u->id, $vip3);
                    $has_vip3 = true;
                }
                $vip4 = $this->set->r4;
                $this->saveCommission($u->id, $vip4, $award_type4, $award_name4);
                $this->equal($u->id, $vip4);
                $has_vip4 = true;
                break;
            }
        }

    }

    // 分红奖
    // public function profit()
    // {
    //     $award_name = '分红奖';
    //     $award_type = 50;
    //
    //     $vip3_1 = 0;
    //     $vip3_2 = 0;
    //     $vip4_1 = 0;
    //     $vip4_2 = 0;
    //
    //     $has_vip3_1 = false;
    //     $has_vip3_2 = false;
    //     $has_vip4_1 = false;
    //     $has_vip4_2 = false;
    //
    //     $chain = Chain::getReferrerChain($this->order->user_id, [], true);
    //     foreach ($chain as $user) {
    //         if ($user->level == UserLevel::$keys['vip1'] || $user->level == UserLevel::$keys['vip2']) {
    //             continue;
    //         }
    //
    //         if ((!$has_vip3_1 && !$has_vip3_2 && !$has_vip4_1 && !$has_vip4_2) && $user->level == UserLevel::$keys['vip3']) {
    //             $vip3_1 = $this->set->p3_1;
    //             $this->saveCommission($user->id, $vip3_1, $award_type, $award_name);
    //             $has_vip3_1 = $user->id;
    //         }
    //         if ((!$has_vip3_2 && !$has_vip4_1 && !$has_vip4_2) && $user->level == UserLevel::$keys['vip3']) {
    //             if ($has_vip3_1 == $user->id) {
    //                 continue;
    //             }
    //             $vip3_2 = $this->set->p3_2;
    //             $this->saveCommission($user->id, $vip3_2, $award_type, $award_name);
    //             $has_vip3_2 = $user->id;
    //         }
    //         if ((!$has_vip4_1 && !$has_vip4_2) && $user->level == UserLevel::$keys['vip4']) {
    //             $vip4_1 = $this->set->p4_1;
    //             $this->saveCommission($user->id, $vip4_1, $award_type, $award_name);
    //             $has_vip4_1 = $user->id;
    //         }
    //         if ((!$has_vip4_2) && $user->level == UserLevel::$keys['vip4']) {
    //             if ($has_vip4_1 == $user->id) {
    //                 continue;
    //             }
    //             $vip4_2 = $this->set->p4_2;
    //             $this->saveCommission($user->id, $vip4_2, $award_type, $award_name);
    //             $has_vip4_2 = $user->id;
    //             break;
    //         }
    //     }
    // }

    // 推荐奖
    // public function recommend()
    // {
    //     $award_name1 = '推荐奖';
    //     $award_type1 = 11;
    //     $award_name2 = '团队奖';
    //     $award_type2 = 12;
    //
    //     $amount = $this->order->total_pay - $this->order->total_freight;
    //
    //     if ($amount >= $this->set->vip1) {
    //
    //         // 送积分
    //         $this->saveScore($this->user->id, $amount);
    //
    //         $r1 = Chain::getReferrer($this->user->id, true);
    //         if ($r1) {
    //             if ($r1->level >= UserLevel::$keys['vip2']) {
    //                 $commission = 0;
    //                 if ($r1->level == UserLevel::$keys['vip2']) {
    //                     $commission = $this->set->r2;
    //                 }
    //                 if ($r1->level == UserLevel::$keys['vip3']) {
    //                     $commission = $this->set->r3;
    //                 }
    //                 if ($r1->level == UserLevel::$keys['vip4']) {
    //                     $commission = $this->set->r4;
    //                 }
    //                 $this->saveCommission($r1->id, $commission, $award_type1, $award_name1);
    //             } else {
    //                 $commission = $this->set->r1;
    //                 $this->saveCommission($r1->id, $commission, $award_type1, $award_name1);
    //
    //                 $r2 = Chain::getReferrer($r1->id, true);
    //                 if ($r2) {
    //                     $commission = 0;
    //                     if ($r2->level == UserLevel::$keys['vip2']) {
    //                         $commission = $this->set->r2 - $this->set->r1;
    //                     }
    //                     if ($r2->level == UserLevel::$keys['vip3']) {
    //                         $commission = $this->set->r3 - $this->set->r1;
    //                     }
    //                     if ($r2->level == UserLevel::$keys['vip4']) {
    //                         $commission = $this->set->r4 - $this->set->r1;
    //                     }
    //                     $this->saveCommission($r2->id, $commission, $award_type2, $award_name2);
    //                 }
    //             }
    //         }
    //     }
    //
    // }

    // 平级奖
    // public function equal()
    // {
    //     // 这里不用算商品数量了, 因为是根据奖金的百分比来返的
    //
    //     $award_name = '平级奖';
    //     $award_type = 210;
    //
    //     $vip2 = 0;
    //     $vip2_2 = 0;
    //     $vip3 = 0;
    //     $vip3_2 = 0;
    //     $vip4 = 0;
    //     $vip4_2 = 0;
    //
    //     $has_vip2 = false;
    //     $has_vip2_2 = false;
    //     $has_vip3 = false;
    //     $has_vip3_2 = false;
    //     $has_vip4 = false;
    //     $has_vip4_2 = false;
    //
    //     $chain = Chain::getReferrerChain($this->order->user_id, [], true);
    //
    //     foreach ($chain as $user) {
    //         if ($user->level == UserLevel::$keys['vip1']) {
    //             continue;
    //         }
    //
    //         if (((!$has_vip2 || !$has_vip2_2) && !$has_vip3 && !$has_vip4) && $user->level == UserLevel::$keys['vip2']) {
    //             if ($vip2 == 0) {
    //                 $vip2 = $this->_equal($user->id) * $this->set->equal / 100;
    //             } else {
    //                 if ($vip2_2 == 0) {
    //                     $this->saveCommission($user->id, $vip2, $award_type, $award_name);
    //                     $vip2_2 = $vip2  * $this->set->equal / 100;
    //                     $has_vip2 = true;
    //                 } else {
    //                     $this->saveCommission($user->id, $vip2_2, $award_type, $award_name);
    //                     $has_vip2_2 = true;
    //                 }
    //             }
    //         }
    //         if (((!$has_vip3 || !$has_vip3_2) && !$has_vip4) && $user->level == UserLevel::$keys['vip3']) {
    //             if ($vip3 == 0) {
    //                 $vip3 = $this->_equal($user->id) * $this->set->equal / 100;
    //             } else {
    //                 if ($vip3_2 == 0) {
    //                     $this->saveCommission($user->id, $vip3, $award_type, $award_name);
    //                     $vip3_2 = $vip3  * $this->set->equal / 100;
    //                     $has_vip3 = true;
    //                 } else {
    //                     $this->saveCommission($user->id, $vip3_2, $award_type, $award_name);
    //                     $has_vip3_2 = true;
    //                 }
    //             }
    //         }
    //         if (((!$has_vip4 || !$has_vip4_2)) && $user->level == UserLevel::$keys['vip4']) {
    //             if ($vip4 == 0) {
    //                 $vip4 = $this->_equal($user->id) * $this->set->equal / 100;
    //             } else {
    //                 if ($vip4_2 == 0) {
    //                     $this->saveCommission($user->id, $vip4, $award_type, $award_name);
    //                     $vip4_2 = $vip4  * $this->set->equal / 100;
    //                     $has_vip4 = true;
    //                 } else {
    //                     $this->saveCommission($user->id, $vip4_2, $award_type, $award_name);
    //                     $has_vip4_2 = true;
    //                 }
    //             }
    //         }
    //     }
    // }

    // private function _equal($user_id)
    // {
    //     // 获取收益
    //     $total = UserCommission::find()
    //         ->where(['user_id' => $user_id])
    //         ->andWhere(['order_id' => $this->order->id])
    //         // 只取直推, 团队(间推)
    //         ->andWhere(['award_type' => [201, 202, 203, 204]])
    //         // 待返的也算
    //         ->sum('balance');
    //
    //     return floatval($total);
    // }

    // 根据产品, 获取佣金
    // private function getCommissionByProduct($id)
    // {
    //     return SetProductCommission::find()
    //         ->where(['product_id' => $id])
    //         ->one();
    // }

    // 保存积分
    protected function saveScore($user_id, $score)
    {
        if ($score >= 0.01) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $this->user->id;
            $model->order_id = $this->order->id;
            $model->score = $score;
            $model->status = 1;
            $model->award_name = '下单送积分';
            $model->award_type = 1;
            $model->save();

            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {
                $account->score += $score;
                $account->save();
            }
        }
    }

    // 有没有帮扶
    public static function hasHelp($user_id)
    {
        $list = Chain::getChildrenLevel($user_id, [
            UserLevel::$keys['vip1'],
            UserLevel::$keys['vip2'],
            UserLevel::$keys['vip3'],
            UserLevel::$keys['vip4']
        ]);
        if (!$list || count($list) < 2) {
            return false;
        }

        $c1 = Chain::getChildrenLevel($list[0]['id'], [
            UserLevel::$keys['vip1'],
            UserLevel::$keys['vip2'],
            UserLevel::$keys['vip3'],
            UserLevel::$keys['vip4']
        ]);
        if (!$c1 || count($c1) < 2) {
            return false;
        }

        $c2 = Chain::getChildrenLevel($list[1]['id'], [
            UserLevel::$keys['vip1'],
            UserLevel::$keys['vip2'],
            UserLevel::$keys['vip3'],
            UserLevel::$keys['vip4']
        ]);
        if (!$c2 || count($c2) < 2) {
            return false;
        }

        return true;
    }

    protected function saveCommission2($user_id, $balance, $type, $name)
    {
        if ($balance >= 0.01) {

            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $this->user->id;
            $model->order_id = $this->order->id;
            $model->balance = $balance;
            $model->status = 1;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();


            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {
                $account->balance += $balance;
                $account->save();
            }
        }
    }

    // 保存佣金
    protected function saveCommission($user_id, $balance, $type, $name)
    {
        if ($balance >= 0.01) {

            // 有没有帮扶
            $has = Award::hasHelp($user_id);
            if (!$has) {
                $commission = $balance * 0.8;
                $commission_await = $balance * 0.2;

                $model = new UserCommission();
                $model->user_id = $user_id;
                $model->fans_id = $this->user->id;
                $model->order_id = $this->order->id;
                $model->balance = $commission;
                $model->status = 1;
                $model->award_name = $name;
                $model->award_type = $type;
                $model->save();

                $model = new UserCommission();
                $model->user_id = $user_id;
                $model->fans_id = $this->user->id;
                $model->order_id = $this->order->id;
                $model->balance = $commission_await;
                $model->status = 0;
                $model->award_name = $name;
                $model->award_type = $type;
                $model->save();
            } else {
                $commission = $balance;
                $commission_await = 0;

                $model = new UserCommission();
                $model->user_id = $user_id;
                $model->fans_id = $this->user->id;
                $model->order_id = $this->order->id;
                $model->balance = $commission;
                $model->status = 1;
                $model->award_name = $name;
                $model->award_type = $type;
                $model->save();
            }



            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {
                $account->balance += $commission;
                $account->await_balance += $commission_await;
                $account->save();
            }
        }
    }

    // 2+1 间推
    private function getIndirect($user_id)
    {
        $the_referrer = Chain::getReferrer($user_id, true);
        if (!$the_referrer) {
            return null;
        }

        // 高等级
        if ($the_referrer->level >= UserLevel::$keys['vip3']) {
            // return $the_referrer;
        }

        // 处理两线条
        if ($the_referrer->level >= UserLevel::$keys['vip2']) {

            // 判断是否属于前2个直推
            $children = Chain::getChildrenSort($the_referrer->id, ['id']);

            // if (count($children) > $this->set->vip2) {
            if (count($children) >= 2) {
                $children = [$children[0], $children[1]];
                $in = in_array($user_id, $children);
                if (!$in) {
                    return $the_referrer;
                } else {
                    return $this->getIndirect($the_referrer->id);
                }
            } else {
                return $this->getIndirect($the_referrer->id);
            }
        }

        return $this->getIndirect($the_referrer->id);
    }
}